package com.realgodo.site.service.dic;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.dic.Constellation;
import com.realgodo.site.entity.space.Space;
import com.realgodo.site.service.relation.FriendManager;


@Service
@Transactional
public class ConstellationManager extends DefaultEntityManager<Constellation, Long> {
	
	@Autowired
	protected SessionFactory sessionFactory;
	@Autowired
	protected FriendManager friendManager;
	
	@SuppressWarnings("unchecked")
	
	/**星座及朋友列表*/
	public List<Constellation> getConstellations(Long spaceId){
		
		Criteria c = sessionFactory.getCurrentSession().createCriteria(Constellation.class);
		c.addOrder(Order.asc("startDate"));
		List<Constellation> constellationList=c.list();
		if(spaceId==null||DAFAULT_LONG_NULL_VALUE.equals(spaceId)){
			return constellationList;
		}
		List<Long> relationSpaceIds=friendManager.getFriendSpaceIdList(spaceId);
		if(relationSpaceIds==null||relationSpaceIds.size()==0){
			return new ArrayList<Constellation>();
		}
		c = sessionFactory.getCurrentSession().createCriteria(Space.class);
		c.createAlias("user", "user");
		c.add(Restrictions.in("id", relationSpaceIds));
		c.addOrder(Order.asc("user.birthday"));
		List<Space> friends=c.list();
		if(friends==null||friends.size()==0){
			return constellationList;
		}
		for(Constellation constellation:constellationList){
			for(int i=0;i<friends.size();i++){
				if(ConstellationManager.isConstellation(friends.get(i).getUser().getBirthday(), constellation)){
					constellation.addRelation(friends.get(i));
					friends.remove(i);
					i--;
				}
			}
		}
		return constellationList;
	}
	
	public void deleteConstellation(Long id){
		sessionFactory.getCurrentSession()
		.createQuery("delete from ConstellationBlood o where o.constellation.id = ?")
		.setParameter(0, id)
		.executeUpdate();
		this.delete(id);
	}

	/**判断date是否属于当前Constellation*/
	public static boolean isConstellation(Date date,Constellation constellation){
		if(date==null||constellation==null){
			return false;
		}
		Calendar c=Calendar.getInstance();
		c.setTime(date);
		c.set(Calendar.YEAR, Constellation.DEFAULT_YEAR);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		
		if(c.getTime().before(constellation.getCompareEndDate())&&c.getTime().after(constellation.getStartDate())){
			return true;
		}
		return false;
	}
}
